import React, { useEffect, useState, useRef, useMemo } from 'react';
import ReactECharts from 'echarts-for-react';
import * as echarts from 'echarts';
import { useWindowSize } from '../hooks/useWindowSize';
import hongkongGeoJson from '../data/hongkong.json';

// 香港18区数据
const districts = [
  { name: '中西區', value: 100, id: '810001' },
  { name: '灣仔區', value: 80, id: '810002' },
  { name: '東區', value: 90, id: '810003' },
  { name: '南區', value: 70, id: '810004' },
  { name: '油尖旺區', value: 85, id: '810005' },
  { name: '深水埗區', value: 75, id: '810006' },
  { name: '九龍城區', value: 95, id: '810007' },
  { name: '黃大仙區', value: 65, id: '810008' },
  { name: '觀塘區', value: 88, id: '810009' },
  { name: '葵青區', value: 72, id: '810017' },
  { name: '荃灣區', value: 68, id: '810010' },
  { name: '屯門區', value: 82, id: '810011' },
  { name: '元朗區', value: 78, id: '810012' },
  { name: '北區', value: 92, id: '810013' },
  { name: '大埔區', value: 85, id: '810014' },
  { name: '沙田區', value: 88, id: '810016' },
  { name: '西貢區', value: 76, id: '810015' },
  { name: '離島區', value: 60, id: '810018' }
];

const HongKongMap: React.FC = () => {
  const { width } = useWindowSize();
  const [fontSize, setFontSize] = useState(16);
  const [mapHeight, setMapHeight] = useState(400);
  const [mapLoaded, setMapLoaded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const chartRef = useRef<echarts.ECharts | null>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // 处理响应式布局
  useEffect(() => {
    if (width <= 480) {
      setFontSize(12);
      setMapHeight(200);
    } else if (width <= 768) {
      setFontSize(14);
      setMapHeight(250);
    } else if (width <= 992) {
      setFontSize(15);
      setMapHeight(300);
    } else {
      setFontSize(16);
      setMapHeight(400);
    }
  }, [width]);

  // 初始化地图数据
  useEffect(() => {
    const initMap = async () => {
      try {
        // 确保GeoJSON格式正确
        if (hongkongGeoJson.type === 'FeatureCollection' && Array.isArray(hongkongGeoJson.features)) {
          // 暂时使用any类型，后续可以优化类型定义
          echarts.registerMap('hongkong', hongkongGeoJson as any);
          console.log('香港地图注册成功');
          setMapLoaded(true);
          setError(null);
        } else {
          throw new Error('无效的GeoJSON格式，需要FeatureCollection类型');
        }
      } catch (err: any) {
        console.error('加载香港地图数据失败:', err.message);
        setError(`地图数据加载失败: ${err.message}`);
      }
    };

    initMap();

    return () => {
      if (chartRef.current) {
        chartRef.current.dispose();
        chartRef.current = null;
      }
    };
  }, []);

  // 使用useMemo缓存配置
  const option = useMemo(() => ({
    backgroundColor: 'transparent',
    title: {
      text: '香港區域分佈',
      textStyle: {
        color: '#fff',
        fontSize: fontSize,
        fontWeight: 'bold'
      },
      left: 'center',
      top: 10
    },
    tooltip: {
      trigger: 'item',
      formatter: (params: any) => {
        const district = districts.find(d => d.id === params.data.id);
        return `${params.name}<br/>數值: ${district?.value || 0}`;
      },
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: '#00b8d9',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      padding: 10,
      confine: true
    },
    series: [
      {
        name: '香港地圖',
        type: 'map',
        map: 'hongkong',
        roam: true,
        zoom: 1.2,
        center: [114.1694, 22.3193],
        aspectScale: 0.75,
        itemStyle: {
          areaColor: '#1e293b',
          borderColor: '#fff',
          borderWidth: 1,
          borderType: 'solid',
          shadowColor: 'rgba(0, 184, 217, 0.2)',
          shadowBlur: 5
        },
        emphasis: {
          itemStyle: {
            areaColor: '#00b8d9',
            borderColor: '#fff',
            borderWidth: 2,
            shadowColor: 'rgba(0, 184, 217, 0.3)',
            shadowBlur: 10
          },
          label: {
            show: true,
            color: '#fff',
            fontSize: fontSize,
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            padding: [4, 8],
            borderRadius: 4,
            fontWeight: 'bold'
          }
        },
        data: districts,
        label: {
          show: true,
          color: '#fff',
          fontSize: width <= 480 ? 8 : 10,
          backgroundColor: 'rgba(0, 0, 0, 0.7)',
          padding: [2, 4],
          borderRadius: 2,
          formatter: '{b}',
          textStyle: {
            fontSize: width <= 480 ? 8 : 10,
            color: '#fff'
          }
        },
        select: {
          itemStyle: {
            areaColor: '#00b8d9',
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            color: '#fff',
            fontWeight: 'bold',
            show: true
          }
        },
        lineStyle: {
          color: '#fff',
          width: 1,
          type: 'solid',
          opacity: 0.8,
          curveness: 0
        },
        mapValueCalculation: 'sum',
        showLegendSymbol: true,
        nameMap: {
          '810001': '中西區',
          '810002': '灣仔區',
          '810003': '東區',
          '810004': '南區',
          '810005': '油尖旺區',
          '810006': '深水埗區',
          '810007': '九龍城區',
          '810008': '黃大仙區',
          '810009': '觀塘區',
          '810010': '荃灣區',
          '810011': '屯門區',
          '810012': '元朗區',
          '810013': '北區',
          '810014': '大埔區',
          '810015': '西貢區',
          '810016': '沙田區',
          '810017': '葵青區',
          '810018': '離島區'
        }
      }
    ]
  }), [fontSize, width]);

  // 处理图表实例
  const onChartReady = (chart: echarts.ECharts) => {
    console.log('图表实例已创建');
    chartRef.current = chart;
    
    if (mapLoaded) {
      console.log('设置初始图表配置');
      chart.setOption(option, true);

      // 初始化图表尺寸
      if (containerRef.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        chart.resize({ width, height });
      }
    }
  };

  // 监听窗口大小变化
  useEffect(() => {
    if (!chartRef.current || !mapLoaded) return;
    
    const handleResize = () => {
      if (containerRef.current && chartRef.current) {
        const { width, height } = containerRef.current.getBoundingClientRect();
        chartRef.current.resize({ width, height });
      }
    };

    // 初始调用一次
    handleResize();
    
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, [mapLoaded]);

  // 地图加载失败时的显示
  if (error) {
    return (
      <div style={{ 
        height: `${mapHeight}px`, 
        width: '100%', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center', 
        color: '#ff4d4f',
        flexDirection: 'column',
        gap: '10px',
        backgroundColor: '#fff'
      }}>
        <div>{error}</div>
        <button 
          onClick={() => {
            setError(null);
            // 重新初始化地图
            const initMap = async () => {
              try {
                if (hongkongGeoJson.type === 'FeatureCollection' && Array.isArray(hongkongGeoJson.features)) {
                  echarts.registerMap('hongkong', hongkongGeoJson as any);
                  setMapLoaded(true);
                } else {
                  throw new Error('无效的GeoJSON格式，需要FeatureCollection类型');
                }
              } catch (err: any) {
                setError(`地图数据加载失败: ${err.message}`);
              }
            };
            initMap();
          }}
          style={{
            padding: '8px 16px',
            backgroundColor: '#1890ff',
            border: 'none',
            borderRadius: '4px',
            color: '#fff',
            cursor: 'pointer'
          }}
        >
          重试加载地图
        </button>
      </div>
    );
  }

  // 地图加载中时的显示
  if (!mapLoaded) {
    return (
      <div style={{ 
        height: `${mapHeight}px`, 
        width: '100%', 
        display: 'flex', 
        alignItems: 'center', 
        justifyContent: 'center', 
        color: '#fff',
        backgroundColor: 'transparent'
      }}>
        正在加载香港地图数据...
      </div>
    );
  }

  return (
    <div 
      ref={containerRef}
      style={{ 
        height: `${mapHeight}px`, 
        width: '100%',
        position: 'relative',
        overflow: 'hidden',
        backgroundColor: 'transparent'
      }}
    >
      <ReactECharts
        option={option}
        notMerge={true}
        lazyUpdate={false}
        onChartReady={onChartReady}
        opts={{ 
          renderer: 'canvas',
          devicePixelRatio: window.devicePixelRatio
        }}
      />
    </div>
  );
};

export default HongKongMap;